import {WeaForm} from 'comsMobx'
import {observable, action, toJS} from 'mobx';
import {WeaTools } from 'ecCom';
import {WeaLocaleProvider} from "ecCom";
const getLabel = WeaLocaleProvider.getLabel;
import * as conLockApi from '../apis/contractLockSend';
import {Modal} from "antd";
import {WeaBrowser} from "../components/IntegrationForm_Table";


const initDatas = {
    form :new WeaForm(),//状态值
    workflowid :"",//选中的流程路径id
    formtype: "",

}
class CreateFormStores {
    @observable conditioninfo = [];
    @observable dtIdList = [];//存储选中流程id，后台传回
    tabledata = null;
    isorder = false;//签署顺序
    hiddenid = null;
    ispublics = true;//是否公有
    @observable loading = true;//是否加载中
    signnatorys = [];//签署方下拉选项
    customtitle = getLabel(32197, '自定义接口设置')
    addbtns = [
        {name:this.customtitle,index:1, key:"1.1", click: this.setShowInterface,isrightbtn:true, isbottombtn:true, icon:"icon-portal-Journal-o"}
    ];//可能加载的右键菜单
    @observable isShowInterface = false;//显示自定义接口
    @observable alldatas = initDatas ;
    @observable cellss = [];//单元格配置，
    nodestitle = [];//操作权限表头

    nodedatas = [];//节点表格数据



    setFormDatas = (url,params) => {//表单切换  新建getCreateForm--编辑getEditForm
        this.clearstore();
        this.alldatas.form.resetForm();
        if(params && params.formtype) {
            this.alldatas.formtype = params.formtype || "getCreateForm";//给定默认值
        } else {
            this.alldatas.formtype = "getCreateForm";//给定默认值
        }
        conLockApi.currencyRequestPOST(url, params).then(result => {
            //只有契约锁集成才会存在
            result && result.nodestitle && (this.nodestitle = result.nodestitle);//表格title
            result && result.signatorys && (this.signnatorys = result.signatorys);//签署方信息
            result && result.nodedatas && (this.nodedatas = result.nodedatas);//表格数据
            result && result.dtIdList && (this.dtIdList = result.dtIdList);//更新明细字段id
            //end 特有数据处理结束
            this.updateLoading(false);
            this.conditioninfo = result.condition;
            this.hiddenid = result.hiddenid;
            this.isorder = result.isorder;
            this.ispublics = result.ispublic;
            this.alldatas.workflowid = result.hiddenid;
            this.tabledata = toJS(result.tabledatas);//可以用url区别
            this.alldatas.form.initFormFields(toJS(result.condition));
            this.fnupdateInitForm(this.conditioninfo, url, this.ispublics);
        });
    }
    /**
     * 改变节点权限数据
     * @param datas
     */
    updateNodeDatas = (datas = []) => {
        this.nodedatas = datas;
    }

    /**
     * 更新cellss
     * @param cellss
     */
    @action
    updataCellss = (cellss = []) => {
        this.cellss = cellss;
    }

    fnupdateInitForm = (condition, url, ispublic) => {
        let itg, qys, doc, tem;
        let {form} = this.alldatas;
        //特殊处理契约锁服务
        if (url && url.toString().indexOf("/createFormDatas") > 0) {
            itg = {
                viewAttr: "3",
                rules: "required",
                value: form.getFormDatas().integratedLoginId && form.getFormDatas().integratedLoginId.value
            };
            qys = {
                viewAttr: "2",
                rules: false,
                value: form.getFormDatas().isqyslogin && form.getFormDatas().isqyslogin.value
            };
        }
        if(url && url.toString().indexOf("/createInteFormDatas") > 0) {
            //特殊处理契约锁集成  编辑时
            tem = { viewAttr: "2", rules:false, value: form && form.getFormDatas().templateField && form.getFormDatas().templateField.value };
            doc = { viewAttr: "2", rules:false, value: form && form.getFormDatas().documentField && form.getFormDatas().documentField.value};
        }

        if (url && url.toString().indexOf("/createInteFormDatas") > 0  && !tem.value && !doc.value) {//两者都为空时，设置显示必填项
            doc = {viewAttr: "3", rules:"required"}
            tem = {viewAttr: "3", rules:"required"}
        }
        if(!ispublic) {//私有
            if(url && url.toString().indexOf("/createFormDatas") > 0 && qys.value != 1 && !itg.value) {//两者都为空，设置显示必填
                itg = {viewAttr:"3",rules:"required"}
                qys = {viewAttr:"3",rules:"required"}
            }
        }
        const {isFormInit} = this.alldatas.form;
        isFormInit && condition && condition.map(c => {
            //特殊处理契约锁集成
            if (url && url.toString().indexOf("/createInteFormDatas") > 0 && c.type == "contractmsg" ) {
                c.items && c.items.map(field => {
                    if (field.domkey == "templateField") {
                        field.viewAttr = tem && tem.viewAttr;
                        field["rules"] = tem && tem.rules || false;
                    }
                    if (field.domkey == "documentField") {
                        field.viewAttr = doc && doc.viewAttr;
                        field["rules"] = doc && doc.rules ;
                    }
                })
            }
            if (url && url.toString().indexOf("/createFormDatas") > 0) {
                c.items && c.items.map(field => {
                    if (field.domkey == "integratedLoginId" && ispublic) {
                        field.viewAttr = itg && itg.viewAttr;
                        field["rules"] = itg && itg.rules
                    }
                })
            }
        });
        this.setConditioninfo(toJS(condition));
        this.alldatas.form.initFormFields(toJS(condition));
    }

    setWorkflowid = id => this.alldatas.workflowid = id;//设置id用选中后修改

    @action
    setConditioninfo = (param=null) =>{
        this.conditioninfo = param;
    }

    @action setTabledata = (datas ) => this.tabledata = datas;

    @action setIsorder = (isorder=false) => this.isorder = isorder;

    getFormParams() {
        return this.alldatas.form.getFormParams();
    }

    @action setShowInterface = (ok = false) => {
        this.isShowInterface = ok;
    }

    @action updateLoading =(ok = false) => this.loading = ok;
    @action setIspublics = (isok = !this.ispublics) => this.ispublics = isok;

    @action clearstore = () => {
        this.alldatas.form = new WeaForm();
        this.tabledata = null;
        this.hiddendi = null;
        //this.signnatorys = [];
    }

    @action
    doCheckWorkflowidIsUsed = (wfid, groupid, callback) => {
        const _this = this;
        WeaTools.callApi(`/api/contractlock/get/isInteById`, 'POST', {wfid: wfid, groupid: groupid}).then(result => {//0表示配置，1表示没有配置
            let fce = callback;
            _this.setTabledata([]);//清空签署信息
            if (result.status == 1) {
                if (result.isInteById == 0) {//已配置
                    Modal.error({
                        title: getLabel(15172, "系统提示"),
                        content: result.msg ? result.msg : getLabel(505258,"流程已配置，请重新选择流程!"),
                        onOk() {
                            _this.alldatas.form.setField("workflowid", _this.alldatas.form.getField("workflowid").value = "");
                            fce(_this, "");
                        },
                    });
                } else if(result.isInteById == 2) {//本groupid需要重新开发
                    Modal.error({
                        title: getLabel(15172, "系统提示"),
                        content: result.msg ? result.msg : getLabel(32140, "异常，请联系管理员!"),
                        onOk() {
                            _this.alldatas.form.setField("workflowid", _this.alldatas.form.getField("workflowid").value = "");
                            fce(_this, "");
                        },
                    });
                } else {
                    //选择流程时动态更改合同操作权限设置
                    result && result.nodedatas && (_this.nodedatas = result.nodedatas);

                    //选择流程时动态更改明细字段
                    result.detail && this.onChangeDetail(result);

                    //流程改变时的回调，给与流程关联的字段添加流程id
                    fce(_this, wfid);
                }
            } else {
                Modal.error({
                    title: getLabel(15172, "系统提示"),
                    content: result.msg ? result.msg : "请求异常，请稍后重试!",
                    onOk() {
                        fce(_this, "");
                    }
                });
            }
        });
    }

    /**
     * 选择流程时动态改变明细字段
     */
    onChangeDetail=(result)=>{
        this.dtIdList = result.detail.dtIdList;//存储该选中流程的id，数组
        let condition = this.conditioninfo;
        let wfparams = {workflowid:this.alldatas.form.getFormDatas().workflowid};
        this.alldatas.form.getFormDatas().serverId && (wfparams["serverId"]= this.alldatas.form.getFormDatas().serverId)
        this.clearstore();
        let conditionold = [];//存储最原始的condition值
        for(var i =0;i<5;i++){
            conditionold.push(condition[4].items[i]);
        }
        condition[4].items = [...conditionold,...result.detail.dtList];
        this.alldatas.form.initFormFields(condition)
        this.alldatas.form.setCondition(condition)
        this.setConditioninfo(toJS(condition));
        this.alldatas.form.updateFields(wfparams)
    }

    /**
     * 数据的整合处理
     */
    dataprocessing = (param) =>{
        let viewNode = "", downloadNode = "", preSignNode="", printNode="", editSignatoryNode="";
        this.nodedatas && this.nodedatas.map(item => {
            item.viewNode && (viewNode += ","+ item.id);
            item.downloadNode && (downloadNode += "," + item.id);
            item.preSignNode && (preSignNode += "," + item.id);
            item.printNode && (printNode += "," + item.id);
            item.editSignatoryNode && (editSignatoryNode += "," + item.id);
        });
        viewNode.startsWith(",") && (viewNode = viewNode.substring(1));
        downloadNode.startsWith(",") && (downloadNode = downloadNode.substring(1));
        preSignNode.startsWith(",") && (preSignNode = preSignNode.substring(1));
        printNode.startsWith(",") && (printNode = printNode.substring(1));
        editSignatoryNode.startsWith(",") && (editSignatoryNode = editSignatoryNode.substring(1));
        param = {...param, viewNode ,downloadNode, preSignNode, printNode, editSignatoryNode};
        return param;
    }

    /**
     * 手动验证表格数据是否填写完整,保证绕晕代码
     * @returns {boolean}
     */
    doValidate = () => {
        let canSave = true;
        const isp = this.ispublics;
        let isedit = this.alldatas.form.getFormDatas() && this.alldatas.form.getFormDatas().signNode;
        this.tabledata && this.tabledata.map((obj) =>{
            obj && ((obj.signerType == "0" &&  !isp) || obj.signerType == "1" || obj.signerType == "2") &&  obj.isSign &&
            (!obj.nameField || obj.nameField.length <= 0)  && (canSave = false);
            obj  && !(isedit) && (!obj.table_signnode || obj.table_signnode.length <= 0)  && (canSave = false);
        })
        return canSave;
    }
}
export  {CreateFormStores};
